import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { RepairWorkflowService } from '../../services/repair-workflow.service';
import { 
  WorkflowInstance, User, UserRole, PendingTask, 
  StepStatus, WorkflowStatus, RepairPriority 
} from '../../models/repair-workflow.model';

@Component({
  selector: 'app-workflow-tasks',
  templateUrl: './workflow-tasks.component.html',
  styleUrls: ['./workflow-tasks.component.scss']
})
export class WorkflowTasksComponent implements OnInit, OnDestroy {
  private destroy$ = new Subject<void>();
  
  currentUser: User | null = null;
  pendingTasks: PendingTask[] = [];
  allInstances: WorkflowInstance[] = [];
  selectedTask: PendingTask | null = null;
  selectedInstance: WorkflowInstance | null = null;
  
  isLoading = false;
  
  // 枚举引用
  StepStatus = StepStatus;
  WorkflowStatus = WorkflowStatus;
  UserRole = UserRole;
  RepairPriority = RepairPriority;

  constructor(
    private workflowService: RepairWorkflowService,
    private router: Router
  ) {}

  ngOnInit(): void {
    this.loadCurrentUser();
    this.loadData();
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  private loadCurrentUser(): void {
    this.workflowService.currentUser$
      .pipe(takeUntil(this.destroy$))
      .subscribe(user => {
        this.currentUser = user;
        this.loadData(); // 重新加载数据
      });
  }

  loadData(): void {
    this.isLoading = true;
    this.loadPendingTasks();
    this.loadAllInstances();
  }

  private loadPendingTasks(): void {
    this.workflowService.getCurrentUserTasks()
      .pipe(takeUntil(this.destroy$))
      .subscribe(tasks => {
        this.pendingTasks = tasks;
        this.isLoading = false;
      });
  }

  private loadAllInstances(): void {
    this.workflowService.getWorkflowInstances()
      .pipe(takeUntil(this.destroy$))
      .subscribe(instances => {
        this.allInstances = instances;
      });
  }

  selectTask(task: PendingTask | WorkflowInstance): void {
    if ('repairRequest' in task) {
      // 如果是WorkflowInstance，转换为PendingTask格式
      this.selectedTask = {
        id: task.id,
        repairRequestId: task.repairRequestId,
        currentStep: task.currentStep,
        createdAt: task.createdAt,
        repairRequest: {
          id: task.repairRequest.id,
          title: task.repairRequest.title,
          description: task.repairRequest.description,
          priority: task.repairRequest.priority,
          status: task.repairRequest.status,
          device: task.repairRequest.device ? {
            name: task.repairRequest.device.name,
            serialNumber: task.repairRequest.device.serialNumber,
            location: task.repairRequest.device.location
          } : {
            name: 'Unknown Device',
            serialNumber: 'N/A',
            location: 'Unknown'
          }
        }
      };
    } else {
      // 如果是PendingTask
      this.selectedTask = task;
    }
    
    // 加载对应的工作流实例详情
    if (this.selectedTask) {
      this.workflowService.getWorkflowInstance(this.selectedTask.id)
        .pipe(takeUntil(this.destroy$))
        .subscribe(instance => {
          this.selectedInstance = instance;
        });
    }
  }

  onStepCompleted(): void {
    // 步骤完成后重新加载数据
    this.selectedTask = null;
    this.selectedInstance = null;
    this.loadData();
  }

  cancelTask(): void {
    this.selectedTask = null;
    this.selectedInstance = null;
  }

  createNewRequest(): void {
    this.router.navigate(['/repair-request']);
  }

  switchUserRole(role: UserRole | string): void {
    if (typeof role === 'string') {
      role = parseInt(role) as UserRole;
    }
    this.workflowService.switchUserRole(role);
  }

  onRoleChange(event: Event): void {
    const target = event.target as HTMLSelectElement;
    const role = parseInt(target.value) as UserRole;
    this.switchUserRole(role);
  }

  getRoleDisplayName(role: UserRole): string {
    switch (role) {
      case UserRole.TECHNICIAN:
        return '维修工';
      case UserRole.ADMIN:
        return '管理员';
      default:
        return '未知角色';
    }
  }

  getRepairPriorityText(priority: RepairPriority): string {
    return this.workflowService.getRepairPriorityText(priority);
  }

  getRepairPriorityClass(priority: RepairPriority): string {
    switch (priority) {
      case RepairPriority.LOW:
        return 'priority-low';
      case RepairPriority.MEDIUM:
        return 'priority-medium';
      case RepairPriority.HIGH:
        return 'priority-high';
      case RepairPriority.CRITICAL:
        return 'priority-critical';
      default:
        return 'priority-medium';
    }
  }

  getWorkflowStepText(step: string): string {
    return this.workflowService.getWorkflowStepText(step);
  }

  getWorkflowStatusClass(status: WorkflowStatus): string {
    switch (status) {
      case WorkflowStatus.RUNNING:
        return 'status-running';
      case WorkflowStatus.COMPLETED:
        return 'status-completed';
      case WorkflowStatus.CANCELLED:
        return 'status-cancelled';
      case WorkflowStatus.FAILED:
        return 'status-failed';
      default:
        return 'status-unknown';
    }
  }

  trackByTaskId(index: number, task: PendingTask): number {
    return task.id;
  }

  trackByInstanceId(index: number, instance: WorkflowInstance): number {
    return instance.id;
  }

  formatDate(date: Date): string {
    return new Date(date).toLocaleString('zh-CN');
  }

  isTaskPending(instance: WorkflowInstance): boolean {
    return this.pendingTasks.some(t => t.id === instance.id);
  }
} 